package com.ebt.m.utils.android;

import android.os.Handler;
import android.util.Log;

import com.ebt.m.data.middle.EBTFileOption;
import com.ebt.m.data.middle.EBTFilePathHelper;
import com.ebt.m.data.middle.EBTGetAdviceInfo;
import com.ebt.m.data.middle.PolicyNodeMeta;
import com.ebt.m.data.middle.ProductDatainfo;
import com.ebt.m.exception.EBTException.EBTSoapHeaderException;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.DataValidation;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.apache.http.conn.ConnectTimeoutException;

import java.io.File;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 下载帮助类 产品下载，获取消息，名片信息等
 *
 * @author ZhanWu.Li
 */
public class ProductDownloader {

    private static Map<Integer, ArrayList<DownloadController4Product>> productThreads = new ConcurrentHashMap<Integer, ArrayList<DownloadController4Product>>();

    private static String TAG = "ProductDownloader";

    /***
     * 线程池
     */
    public static ExecutorService executor = Executors.newFixedThreadPool(2);

    /**
     * 下载产品
     *
     * @param product 产品信息
     * @param handler
     */
    public static void downloadProduct(final ProductDatainfo product, final Handler handler) {
        if (ConfigData.DEBUG) {
            Log.d(TAG, "downloadProduct DownloadController4Product start");
        }
        try {
            DownloadController4Product downloadController = new DownloadController4Product(product, handler);
            ArrayList threadlist = productThreads.get(product.CompanyId);
            if (threadlist == null) {
                threadlist = new ArrayList<>();
            }
            threadlist.add(downloadController);
            productThreads.put(product.ProductId, threadlist);
            executor.execute(downloadController);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    /***
     * 获取EBT公钥。
     *
     * @return
     * @throws EBTSoapHeaderException
     * @throws UnknownHostException
     * @throws ConnectTimeoutException
     */
    public static String downloadSoapHeaderKey(String user, String password) throws EBTSoapHeaderException, UnknownHostException, ConnectTimeoutException {

		/*
         * if (BuildConfig.DEBUG) { Log.d(TAG,
		 * "downloadSoapHeaderKey user:"+user+"  password"+password ); }
		 */
        String result = "";

        SoapObject soapobj = new SoapObject(DownloaderConstants.URL_USER_KEY_XMLNS, "", "");
        soapobj.setWsURL(DownloaderConstants.URL_USER_KEY_URL);//
        soapobj.setSoapAction(DownloaderConstants.URL_USER_KEY_XMLNS);

        soapobj.setMethod(DownloaderConstants.URL_USER_KEY_METHOD);
        HashMap<String, String> pams = new HashMap<String, String>();

        pams.put("user", user);
        pams.put("password", password);
        soapobj.setParams(pams);
        try {
            result = soapobj.sendRequest();
            if (ConfigData.DEBUG) {
                Log.d(TAG, "jsonStr:" + result);
            }

        } catch (Exception e) {
            //e.printStackTrace();
            //throw new EBTSoapHeaderException(DownloaderConstants.STR_DOWNLOAD_SOAPHEADER_ERROR);
        }

        return result;

    }


    /**
     * 取消下载
     *
     * @param productId
     * @param companyId
     */
    public static void cancel(int productId, int companyId) {

        ArrayList<DownloadController4Product> threadList2 = productThreads.get(productId);

        if (threadList2 != null) {
            for (DownloadController4Product thread : threadList2) {
                // thread.interrupt();
                thread.cancleDownload();

            }
            productThreads.remove(productId);
        }

    }


    /***
     * 在下载list中移除下载productId的线程
     */
    public static void removeDownloadProductThread(int productId) {
        ArrayList<DownloadController4Product> threadList2 = productThreads.get(productId);

        if (threadList2 != null) {
            for (DownloadController4Product thread : threadList2) {
                thread.cancleDownload();
                // thread.interrupt();
            }
            productThreads.remove(productId);
        }
    }



    /**
     * @param
     * @return PolicyNodeMeta
     * @throws
     * @Description: 根据fieldName获得单个节点
     */
    public static PolicyNodeMeta getNodeByFieldName(String fieldName, ArrayList<PolicyNodeMeta> list) {
        if (DataValidation.isEmpty(fieldName)) {
            return null;
        }
        PolicyNodeMeta pnm = null;

        for (int i = 0; i < list.size(); i++) {

            pnm = list.get(i);
            if (pnm != null && fieldName.equalsIgnoreCase(pnm.getFieldName())) {
                return pnm;
            }
        }
        return null;
    }


    /**
     * 判断所有文件是否存在
     *
     * @param fileList
     * @return
     */
    private static boolean isAllFileExist(ArrayList<File> fileList) {

        for (File file : fileList) {
            if (!file.exists()) {

                if (ConfigData.DEBUG) {
                    Log.d(TAG, "file is not exist :" + file.getAbsolutePath());
                }
                return false;
            }
        }
        return true;
    }

    /**
     * 判断产品文件是否都存在
     *
     * @param companyId
     * @param pruductId
     * @return
     */
    public static boolean isProductResExist(int companyId, int pruductId) {
        try {
            String jsonPath = EBTFilePathHelper.getJsonFileName(companyId + "", pruductId + "");
            File file = new File(jsonPath);
            if (!file.exists()) {
                return false;
            }
            ArrayList<File> fileList = new ArrayList<File>();
            EBTFileOption option = new EBTFileOption();

            String jsonValue = null;

            jsonValue = option.EBTReadFile(jsonPath, EBTGetAdviceInfo.getUid());

            JsonParser pa = new JsonParser();
            JsonElement jee = pa.parse(jsonValue);
            JsonElement je = jee.getAsJsonObject().get("productObj");
            jsonValue = je.getAsJsonArray().toString();
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            ArrayList<PolicyNodeMeta> pnmList = gson.fromJson(jsonValue, new TypeToken<ArrayList<PolicyNodeMeta>>() {
            }.getType());

            PolicyNodeMeta pnm = null;
            pnm = getNodeByFieldName(DownloaderConstants.STR_FILE_TYPE_TERM, pnmList);
            if (pnm != null) {

                fileList.add(new File(EBTFilePathHelper.getTermFileName(companyId + "", pruductId + "")));

            }

            pnm = getNodeByFieldName(DownloaderConstants.STR_FILE_TYPE_RULE, pnmList);
            if (pnm != null) {
                fileList.add(new File(EBTFilePathHelper.getRuleFileName(companyId + "", pruductId + "")));
            }

            pnm = getNodeByFieldName(DownloaderConstants.STR_FILE_TYPE_NODE_LIST, pnmList);

            // 检查大费率数据库文件是否存在
//            pnm = getNodeByFieldName(DownloaderConstants.STR_FILE_TYPE_PRODUCT_DB, pnmList);
//            if (pnm != null) {
//                fileList.add(new File(EBTFilePathHelper.getRateDbFileName(companyId + "", pruductId + "")));
//            }


            if (!isAllFileExist(fileList)) {
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /***
     * 下载回调函数
     *
     * @author ZhanWu.Li
     */
    public interface OnDownloadCallBack {
        void onLoading(long count, long current);

        void onSuccess(String result);

        void onStart();

        void onFailure(String message);
    }


}
